import { defineStore } from 'pinia'
import { ref } from 'vue'
import { useMapStore } from './map'
import { usePlayerStore } from './player'
import { useCarGoStore } from './cargo'
import { useTargetStore } from './target'
export const useGameStore = defineStore('game', () => {
  const game = ref({
    isGameCompleted: false, // 游戏是否结束
    level: 1, // 当前关卡
    ispassAll: false,
  })

  let gameData = null
  // 获取全部关卡数据
  function setupGame(data) {
    gameData = data
    setupLevel()
  }
  // 检测游戏是否通关
  function detectionGameCompleted() {
    const { cargos } = useCarGoStore()
    game.value.isGameCompleted = cargos.every((item) => item.onTarget)
  }

  // 下一关
  function nextLevel() {
    if (game.value.level === gameData.length) {
      game.value.ispassAll = true
      return
    }
    game.value.level += 1
    game.value.isGameCompleted = false
    setupLevel()
  }

  function resetLevel() {
    game.value.isGameCompleted = false
    setupLevel()
  }

  // 设置当前关卡
  function setupLevel() {
    const currentLevel = gameData[game.value.level - 1]
    const { setupMap } = useMapStore()
    const { setupPlayer } = usePlayerStore()
    const { setupCargos } = useCarGoStore()
    const { setupTarget } = useTargetStore()
    // 设置地图
    setupMap(currentLevel.map)
    // 设置人物
    setupPlayer(currentLevel.player)
    // 设置箱子
    setupCargos(currentLevel.cargos)
    // 设置点位
    setupTarget(currentLevel.targets)
  }
  return {
    game,
    setupGame,
    nextLevel,
    resetLevel,
    detectionGameCompleted,
  }
})
